package com.maweirdos.ai.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 消息类型处理工具类
 * 用于将Spring AI的消息对象与数据库存储的JSON格式互相转换
 */
public class MessageTypeHandler {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将Message对象转换为JSON字符串
     */
    public static String messageToJson(Message message) {
        try {
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("type", message.getMessageType().getValue());
            
            // 在Spring AI 1.0.0.2中，Message接口没有getContent方法
            // 根据消息类型获取内容
            String content = "";
            if (message instanceof UserMessage) {
                content = ((UserMessage) message).getText();
            } else if (message instanceof AssistantMessage) {
                content = ((AssistantMessage) message).getText();
            } else if (message instanceof SystemMessage) {
                content = ((SystemMessage) message).getText();
            }
            
            messageMap.put("content", content);
            messageMap.put("metadata", message.getMetadata());
            
            return objectMapper.writeValueAsString(messageMap);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to convert message to JSON", e);
        }
    }

    /**
     * 将JSON字符串转换回Message对象
     */
    public static Message jsonToMessage(String json) {
        if (!StringUtils.hasText(json)) {
            return null;
        }
        
        try {
            Map<String, Object> messageMap = objectMapper.readValue(json, Map.class);
            String type = (String) messageMap.get("type");
            String content = (String) messageMap.get("content");
            Map<String, Object> metadata = (Map<String, Object>) messageMap.get("metadata");
            
            return switch (type) {
                case "user" -> new UserMessage(content);
                case "assistant" -> new AssistantMessage(content);
                case "system" -> new SystemMessage(content);
                default -> throw new IllegalArgumentException("Unknown message type: " + type);
            };
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to convert JSON to message", e);
        }
    }
} 